package com.lcc.dingtalk.robot.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author lincc
 * @version 1.0 2020/8/14
 */
public class SignUtil {
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        long timestamp = System.currentTimeMillis();
        String type = "prod";
        System.out.println(timestamp);
        String testAppSecret = "5pVIXBVkmq8bEmUZNPuDlVNlb3wKVP2_IN3zmN_jR4W5x80ifWMAxhDTzjyAyCsp";
        String prodAppSecret = "Bdm3R4rwj06kNFQ2J9oWP0roJN_WVN6zGT0tLMvZGa2Dc7P0sE_8uQ4UT5qPvZO-";
        System.out.println(hmac(String.valueOf(timestamp), "test".equals(type) ? testAppSecret : prodAppSecret));
    }

    public static String hmac(String timestamp, String appSecret) throws NoSuchAlgorithmException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + appSecret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.encodeBase64(signData));
    }
}
